package com.cxh.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @类功能说明：AIUI开发者平台WebApi处理
 * @公司名称：创泽
 * @作者：WangCY
 * @创建时间：2018-5-28 下午5:13:25
 */
public class AiuiUnit {
	private static final String URL = "https://openapi.xfyun.cn/v2/aiui";
	private static final String APPID = "5b0f8dd8"; 
	private static final String API_KEY = "aef516f558fe400f8aff621da9818e56";   
	private static final String DATA_TYPE = "text";
	private static final String SCENE = "car";
	private static String AUTH_ID = ""; 
	
	/**
	 * 
	 * @描述: 测试方法
	 * @作者: WangCY
	 * @日期: 2018-5-28
	 * @修改内容
	 * @参数： @param args
	 * @参数： @throws IOException
	 * @参数： @throws ParseException
	 * @参数： @throws InterruptedException    
	 * @return void   
	 * @throws
	 */
	public static void main(String[] args) throws Exception{
		try {
			loadAiuiApi("税", "003001004210aa17724c");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @描述: 调用AIUI后台并解析
	 * @作者: WangCY
	 * @日期: 2018-5-28
	 * @修改内容
	 * @参数： @param question   问题 （非空）
	 * @参数： @param robotCode  机器人编码 （非空）
	 * @参数： @return
	 * @参数： @throws Exception    
	 * @return String   
	 * @throws
	 */
	public static Map<String, Object> loadAiuiApi(String question, String robotCode) throws Exception{
		Map<String, Object> returnMap = new HashMap<String, Object>();
		// 根据机器人编码生成用户唯一ID
		AUTH_ID = MD5.md5(robotCode); 
		//LogUtil.info("问题：" +question);
		byte[] dataByteArray = question.getBytes("UTF-8");
		Map<String, String> header = buildHeader();
		String result = httpPost(URL, header, dataByteArray);
		//LogUtil.info("AIUI返回结果为：" +result);
		
		if(!CommonUtility.isEmpty(result)){
			// 解析AIUI返回结果JSON串
			Gson gson = new Gson();
			Map<String, Object> resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>(){}.getType());
			if(!CommonUtility.isEmpty(resultMap) && !CommonUtility.isEmpty(resultMap.get("code"))){
				// 返回成功
				if(resultMap.get("code").equals("0")){
					List<Map<String, Object>> dataMap = (List<Map<String, Object>>) resultMap.get("data");
					Map<String, Object> intentMap = (Map<String, Object>) dataMap.get(0).get("intent");
					
					if(!CommonUtility.isEmpty(intentMap.get("answer"))){
						Map<String, Object> answerMap = (Map<String, Object>) intentMap.get("answer");
						// 机器人要说的话
						String answer = (String) answerMap.get("text");
						returnMap.put("answer", answer);
						Map<String, Object> result1Map = (Map<String, Object>) intentMap.get("data");
						// 返回数据是否需要调用处理函数
						if(!CommonUtility.isEmpty(result1Map.get("result"))){
							List<Map<String, Object>> resultList = (List<Map<String, Object>>) result1Map.get("result");
							if(!CommonUtility.isEmpty(resultList.get(0).get("function"))){
								// 返回的参数信息（词槽获取到的）
								returnMap.put("params", resultList.get(0).get("data"));
								// 返回的需要调用的函数名（云函数中定义的）
								returnMap.put("function", resultList.get(0).get("function"));
							}
							if(!CommonUtility.isEmpty(resultList.get(0).get("page"))){
								// 返回的page的标识
								returnMap.put("page", resultList.get(0).get("page"));
							}
						}
						return returnMap;
					}
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 
	 * @描述: 生成调用接口Header
	 * @作者: WangCY
	 * @日期: 2018-5-28
	 * @修改内容
	 * @参数： @return
	 * @参数： @throws UnsupportedEncodingException
	 * @参数： @throws ParseException    
	 * @return Map<String,String>   
	 * @throws
	 */
	private static Map<String, String> buildHeader() throws UnsupportedEncodingException, ParseException {
		String curTime = System.currentTimeMillis() / 1000L + "";
		String param = "{\"auth_id\":\""+AUTH_ID+"\",\"result_level\":\"plain\",\"data_type\":\""+DATA_TYPE+"\",\"scene\":\""+SCENE+"\"}";		
		String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
		String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);

		Map<String, String> header = new HashMap<String, String>();
		header.put("X-Param", paramBase64);
		header.put("X-CurTime", curTime);
		header.put("X-CheckSum", checkSum);
		header.put("X-Appid", APPID);
		return header;
	}
	
	/**
	 * 
	 * @描述: 调用AIUI接口
	 * @作者: WangCY
	 * @日期: 2018-5-28
	 * @修改内容
	 * @参数： @param url
	 * @参数： @param header
	 * @参数： @param body
	 * @参数： @return    
	 * @return String   
	 * @throws
	 */
	private static String httpPost(String url, Map<String, String> header, byte[] body) {
		String result = "";
		BufferedReader in = null;
		OutputStream out = null;
		try {
			URL realUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
			for (String key : header.keySet()) {
				connection.setRequestProperty(key, header.get(key));
			}
			connection.setDoOutput(true);
			connection.setDoInput(true);

			try {
				out = connection.getOutputStream();
				out.write(body);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			try {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
